package org.example.rubbish.service.impl;


import org.example.rubbish.entity.User;
import org.example.rubbish.mapper.UserMapper;
import org.example.rubbish.service.UserService;
import org.example.rubbish.util.SaltUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.List;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;

    @Override
    public User createUser(User user) {
        String salt = SaltUtil.generateSalt();
        user.setSalt(salt);
        String password = DigestUtils.md5DigestAsHex((user.getPassword() + salt).getBytes());
        user.setPassword(password);
        userMapper.insert(user);
        return user;
    }

    @Override
    public User updateUser(User user) {
        userMapper.update(user);
        return userMapper.selectById(user.getId());
    }

    @Override
    public void changePassword(Long userId, String newPassword) {
        User user = userMapper.selectById(userId);
        String salt = user.getSalt();
        String password = DigestUtils.md5DigestAsHex((newPassword + salt).getBytes());
        user.setPassword(password);
        userMapper.updatePassword(user);
    }

    @Override
    public User getUserById(Long id) {
        return userMapper.selectById(id);
    }

    @Override
    public User getUserByUsername(String username) {
        return userMapper.selectByUsername(username);
    }

    @Override
    public List<User> getAllUsers() {
        return userMapper.selectAll();
    }

    @Override
    public List<User> getUsersByBlacklist(Boolean isBlacklist) {
        return userMapper.selectByBlacklist(isBlacklist);
    }

    @Override
    public void addToBlacklist(Long userId) {
        User user = userMapper.selectById(userId);
        user.setIsBlacklist(true);
        userMapper.update(user);
    }

    @Override
    public void removeFromBlacklist(Long userId) {
        User user = userMapper.selectById(userId);
        user.setIsBlacklist(false);
        userMapper.update(user);
    }
}
